package com.example.springbootvue.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springbootvue.common.Result;
import com.example.springbootvue.entity.Book;
import com.example.springbootvue.mapper.BookMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    BookMapper bookMapper;

    @PostMapping //新增
    public Result<?> save(@RequestBody Book book){

        bookMapper.insert(book);
        System.out.println(book);
        return Result.success();
    }

    @GetMapping     //查询
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){

        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
        if(StrUtil.isNotBlank(search)){
            wrapper.like(Book::getName,search);
        }
        Page<Book> bookPage = bookMapper.selectPage(new Page<>(pageNum, pageSize),wrapper);//::=get(可以直接访问属性)
        return Result.success(bookPage);
    }

    @PutMapping    //更新
    public Result<?> update(@RequestBody Book book){
        bookMapper.updateById(book);

        return Result.success();
    }

    @DeleteMapping("/{id}")    //删除
    public Result<?> delete(@PathVariable long id){
        bookMapper.deleteById(id);
        return Result.success();
    }


    //批量删除
    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids){
        bookMapper.deleteBatchIds(ids);
        return Result.success();
    }
}
